<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<script>
		var p1 = new LcPromise((resolve, reject) => {
			setTimeout(() => {
				resolve({ test: 1 })
			}, 1000)
		})
		p1.then((data) => {
			console.log('result1', data)
			return "p1.then的结果"
		}).then((data) => {
			console.log('result2', data)
			debugger
		})
		p1.then((data) => {
			console.log('result3', data)
		})


		function LcPromise(fn) {
			let state = 'pending';//fulfilled//rejected;
			let value = null;
			// 将未来需要调用的函数，放置到callbacks里
			const callbacks = []
			// onFulfilled是成功执行的回调函数的参数
			this.then = function (onFulfilled) {
				return new LcPromise((resolve, reject) => {
					handle({
						onFulfilled,
						resolve
					})
				})
			}

			function handle(callback) {
				if (state === 'pending') {
					callbacks.push(callback);
					return;
				}

				if (state === 'fulfilled') {
					if (!callback.onFulfilled) {
						callback.resolve(value)
						return;
					}
					// 处理then的回调函数
					const ret = callback.onFulfilled(value);
					// 将结果传给下一个promise的resolve函数
					callback.resolve(ret)

				}
			}

			function resolve(newValue) {

				setTimeout(() => {
					// 如果状态已经发生了改变，那么直接跳出去
					if (state !== 'pending') return;
					state = 'fulfilled';
					value = newValue;

					handleCb()
				}, 0);


			}

			function handleCb() {
				while (callbacks.length) {
					const fulfilledFn = callbacks.shift();
					handle(fulfilledFn)
				}
			}


			fn(resolve)





		}
	</script>
</body>

</html>